package cn.lds.health.service.impl;

import cn.lds.health.constant.DsHealthConstant;
import cn.lds.health.dto.ResultDTO;
import cn.lds.health.entity.HealthExamItem;
import cn.lds.health.entity.HealthExamPackage;
import cn.lds.health.exception.SysException;
import cn.lds.health.mapper.HealthExamItemMapper;
import cn.lds.health.mapper.HealthExamPackageMapper;
import cn.lds.health.service.HealthExamPackageService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import java.util.List;
import java.util.Objects;

/**
 * @ClassName healthExamPackageServiceImpl
 * @Description TODO
 * @Author Christopher
 * @Date 2023/8/6 16:20
 * @Version 1.0
 **/

@Service
public class healthExamPackageServiceImpl implements HealthExamPackageService {
	
	@Autowired
	private HealthExamPackageMapper healthExamPackageMapper;
	
	
	@Transactional(propagation = Propagation.SUPPORTS,readOnly = true)
	@Override
	public ResultDTO<List<HealthExamPackage>> selectHealthPackageAll() throws SysException {
		
		List<HealthExamPackage> healthExamPackages = healthExamPackageMapper.selectHealthPackageAll();
		
		if (CollectionUtils.isEmpty(healthExamPackages)){
			throw new SysException(DsHealthConstant.Query.QUERY_ERROR);
		}
		
		return ResultDTO.buildSuccess(healthExamPackages);
	}
	
	@Transactional(propagation = Propagation.SUPPORTS,readOnly = true)
	@Override
	public ResultDTO<HealthExamPackage> selectHealthPackageById(Integer id) throws SysException {
		
		HealthExamPackage healthExamPackage = healthExamPackageMapper.selectHealthPackageById(id);
		
		if (Objects.isNull(healthExamPackage)){
			throw new SysException(DsHealthConstant.Query.QUERY_ERROR);
		}
		
		
		return ResultDTO.buildSuccess(healthExamPackage);
	}
	
	@Transactional(propagation = Propagation.REQUIRED,readOnly = false)
	@Override
	public ResultDTO addHealthExamPackage(HealthExamPackage healthExamPackage,Integer... iIds) throws SysException {
		
		int i = healthExamPackageMapper.addHealthExamPackage(healthExamPackage);
		
		if (i <= 0){
			throw new SysException(DsHealthConstant.Insert.ADD_ERROR);
		}
		//插入体检套餐数据，获取主键
		Integer pid = healthExamPackage.getId();

		//遍历参数，1对多插入体检项目数据
		for (Integer iId : iIds) {
			int i1 = healthExamPackageMapper.addPackageItem(pid, iId);
		}
		return ResultDTO.buildSuccess();
	}
}